import requests
import json
import time

headers = {
    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36 Edg/105.0.1343.27"
}

# 登录
def getLoginCookie(id:str, pwd:str):
    login = "https://libic.njfu.edu.cn/ClientWeb/pro/ajax/login.aspx"
    data = {
        "id":id,
        "pwd":pwd,
        "act":"login"
    }
    res = requests.post(url=login, data=data, headers=headers)
    return res.cookies

# 获取学生id stuform[0]['id']
def getStuForm(stu:str, cookie):
    qstu = f"https://libic.njfu.edu.cn/ClientWeb/pro/ajax/data/searchAccount.aspx?type=logonname&ReservaApply=ReservaApply&term={stu}"
    res = requests.get(url=qstu, headers=headers, cookies=cookie)
    return json.loads(res.text)

# 格式转换mb_list
def getMBLIST(mbs:list, cookie):
    mb_list = ""
    for mb in mbs:
        stuform = getStuForm(mb, cookie=cookie);
        if not stuform[0]:
            continue
        stuid = stuform[0]['id']
        if not mb_list:
            mb_list += f"%24{stuid}"
        else:
            mb_list += f"%2C{stuid}"
    return mb_list

# 获取研讨室id
room2id = {}
def getRoomByName(roomName:str, cookie):
    if not room2id:
        now_day = time.strftime("%Y%m%d", time.localtime())
        url = f"https://libic.njfu.edu.cn/ClientWeb/pro/ajax/device.aspx?dev_order=&kind_order=&classkind=1&display=cld&md=d&kind_id=100501645&purpose=&selectOpenAty=&cld_name=default&date={now_day}&act=get_rsv_sta&_=1669096496663"
        res = requests.get(url=url, cookies=cookie)
        data = json.loads(res.text)['data']
        for room in data:
            room2id[room["title"][0:5]] = room["devId"]
    return room2id[roomName]

# 抢研讨室
def postSRoom(theme:str, room:str ,start_time:str, end_time:str, mbs, cookie):
    """抢研讨室

    Args:
        theme (str): 主题
        room (str): 研讨室房间
        start_time (str): 开始时间
        end_time (str): 结束时间
        mbs (_type_): 结束时间
        cookie (_type_): 登录cookie
    Return:
        返回json, 
        ret字段为1表示成功, 为0表示失败
        msg字段为消息
    """
    devId = getRoomByName(room, cookie=cookie)
    if isinstance(mbs, list):
        mb_list = getMBLIST(mbs, cookie=cookie)
    elif isinstance(mbs, str):
        mb_list  = mbs
    url = f"https://libic.njfu.edu.cn/ClientWeb/pro/ajax/reserve.aspx\
?dialogid=&dev_id={devId}&lab_id=&kind_id=&room_id=&type=dev\
&prop=&test_id=&term=&Vnumber=&classkind=&test_name={theme}\
&min_user=4&max_user=8&mb_list={mb_list}&start={start_time}&end={end_time}&up_file=&memo=&act=set_resv&_=1669031323771"
    res = requests.get(url=url ,cookies=cookie)
    return json.loads(res.text)
    


if __name__ == "__main__":
    """
    具体怎么抢，可以自行决定，函数接口已经提供；
    以下可以算作示例：
    我需要抢11月26日10:00~14:00和14:00~18:00的8A508
    由于仅可抢3天后的研讨间
    所以在11月22日23:59分运行该脚本
    """
    # 获取登录信息
    cookie = getLoginCookie(id="<你的账号>", pwd="<你的密码>")
    # 小伙伴的学号
    mbs = ["<学号1>", "<学号2>", "<学号3>", "<学号4>"]
    mbs = getMBLIST(mbs, cookie)
    
    # 具体的研讨室
    room = "8A508"
    # 开始结束时间
    times = [
        {
            "start":"2022-11-26+10:00",
            "end":"2022-11-26+14:00"
        },
        {
            "start":"2022-11-26+14:00",
            "end":"2022-11-26+18:00"
        }
    ]
    # 主题
    theme="练习"

    # 具体逻辑
    prog_start = time.time()
    print(time.strftime("%Y-%m-%d+%H:%M:%S", time.localtime()))
    cnt = 0
    while True:
        for t in times:
            ret = postSRoom(theme=theme, room=room, 
                            start_time=t["start"], end_time=t["end"],
                            mbs=mbs, cookie=cookie)
            print(room, t)
            print(ret)
            if ret["ret"] == 1:
                cnt = cnt + 1
        if cnt == 2:
            print("Done!")
            break
        if time.time() - prog_start >= 200:
            print("TLE")
            break
        time.sleep(0.2)